package cn.edu.xmu.orderpayment.payment.mq.listener;

import cn.edu.xmu.oomall.core.util.ReturnObject;
import cn.edu.xmu.orderpayment.payment.constants.Constants;
import cn.edu.xmu.orderpayment.payment.controller.PayController;
import cn.edu.xmu.orderpayment.payment.dao.PayDao;
import cn.edu.xmu.orderpayment.payment.mq.obj.AfterSaleMessageBody;
import cn.edu.xmu.orderpayment.payment.util.baseobject.PaymentInfo;
import cn.edu.xmu.orderpayment.payment.model.bo.PayPattern;
import cn.edu.xmu.orderpayment.payment.model.bo.Payment;
import cn.edu.xmu.orderpayment.payment.mq.RocketMQService;
import cn.edu.xmu.orderpayment.payment.util.PayMentPatternLoader;
import cn.edu.xmu.orderpayment.payment.util.paypattern.BasePaymentPattern;
import cn.edu.xmu.privilegegateway.annotation.util.JacksonUtil;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;

import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;

/**
 * @author Yujie Lin
 * @date 2021/12/14 8:24
 */

@Service
@RocketMQMessageListener(topic = "pay-check-topic2",  consumeMode = ConsumeMode.CONCURRENTLY, consumeThreadMax = 10, consumerGroup = "pay-check-group2")
public class PayCheckListener implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {

    private final Logger logger = LoggerFactory.getLogger(PayCheckListener.class);


    @Autowired
    private PayMentPatternLoader loader;

    @Autowired
    private PayDao payDao;

    @Autowired
    private RocketMQService rocketMQService;

    // 消费者收到支付检查消息，获得第三方支付信息查看是否已经支付，若已支付则通知订单
    @Override
    public void onMessage(String json) {
        logger.info(LocalDateTime.now()+":支付系统延迟收到消息，现在去第三方检查支付结果");
        Payment payment= JacksonUtil.toObj(json,Payment.class);
        Long patternId=payment.getPatternId();
        ReturnObject<PayPattern> patternRet=payDao.getPayPatternById(patternId);

        String className=patternRet.getData().getClassName();

        try {
            // 如果已支付则无操作
            ReturnObject<Payment> paymentRet=payDao.getPaymentDetailInfo(payment.getId());
            if(paymentRet.getData()==null)return;
            Payment payment1=paymentRet.getData();
            if(payment1.getState()!= Payment.State.WAIT_PAY)return;

            // 若第三方已支付，系统未支付，则修改支付
            BasePaymentPattern pattern= loader.getPaymentPatternByClassName(className);

            RequestContextHolder.setRequestAttributes(Constants.servletRequestAttributes);

            PaymentInfo paymentInfo= pattern.getPayment(payment.getId().toString());

            logger.info(LocalDateTime.now()+":检查的结果："+paymentInfo);

            if(paymentInfo.getState()== Payment.State.HAS_PAYED){
                payment1.setState(Payment.State.HAS_PAYED);
                payment1.setActualAmount(paymentInfo.getRealAmount());
                payment1.setPayTime(paymentInfo.getSuccessTime());
                payment1.setTradeSn(paymentInfo.getTradeSn());
                payDao.modifyPaymentInfo(payment1,payment1.getCreatorId(),payment1.getCreatorName());
                // 通知订单已支付
                if(payment1.getDocumentType()== Payment.DocumentType.NORMAL){
                    rocketMQService.sendSuccessOrderPayMessage(payment1.getDocumentId());
                }
                else if(payment1.getDocumentType()== Payment.DocumentType.AFTERSALE){
                    AfterSaleMessageBody afterSaleMessageBody= new AfterSaleMessageBody(payment1.getDocumentId(),paymentInfo.getRealAmount());
                    String s=JacksonUtil.toJson(afterSaleMessageBody);
                    rocketMQService.sendSuccessServicePayMessage(s);
                }

            }
            //若第三方支付失败，修改支付状态
            else if(paymentInfo.getState()==Payment.State.FAILED_PAY){
                payment1.setState(Payment.State.CANCELED);
                payment1.setTradeSn(paymentInfo.getTradeSn());
                payDao.modifyPaymentInfo(payment1,payment1.getCreatorId(),payment1.getCreatorName());
            }

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {

    }
}
